package com.easytouch.vmhdl.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ant.liao.GifView;
import com.easytouch.core.Configure;
import com.easytouch.core.DriverThread;
import com.easytouch.core.encryption.ETEncrypt;
import com.easytouch.core.listener.OnOutGoodsListener;
import com.easytouch.core.model.ColumnModel;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.task.AvmPayTask;
import com.easytouch.core.task.MobilePayTask;
import com.easytouch.core.task.PickCodeReleaseTask;
import com.easytouch.core.task.TaskThreadPool;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.Tools;
import com.easytouch.vmhdl.AppApplication;
import com.easytouch.vmhdl.R;
import com.easytouch.vmhdl.activity.BaiduFacePayActivity;
import com.easytouch.vmhdl.activity.MainActivity;
import com.easytouch.vmhdl.interfaces.ClickSwitchListener;
import com.easytouch.vmhdl.utils.FileTools;
import com.easytouch.vmhdl.view.BarView;
import com.easytouch.vmhdl.view.BitmapTouchChecker;
import com.easytouch.vmhdl.view.GoodsImageView;
import com.easytouch.vmhdl.view.MainButton;
import com.easytouch.vmhdl.view.MyVideoView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Random;

/**
 * Created by gulin on 2017/12/1.
 */

public class PayFragment extends BaseFragment implements View.OnClickListener, ClickSwitchListener, OnOutGoodsListener {

    public static final String PARAM_GOODS = "GoodsItem"; //商品
    public static final String PARAM_CODE = "code"; //提货码
    public static final String PARAM_IS_SELECT = "isSelect"; //是否是按键选货
    public static final String PARAM_IS_LIST = "isList"; //是否从列表页过来的

    private static final int COUNT_DOWN = 60;
    private static final int COUNT_DOWN_RESULT = 3;

    private static final int PAY_STATE_CHOOSE = 0;
    private static final int PAY_STATE_CASH = 1;
    private static final int PAY_STATE_CARD = 2;
    private static final int PAY_STATE_MOBILE = 3;
    private static final int PAY_STATE_RESULT = 4;
    private static final int PAY_STATE_FACE = 5;

    private Log mLogger = new Log("PayFragment.txt");

    private int mDuration = COUNT_DOWN; // 倒计时
    private MyHandler mHandler;

    private MainButton zhezhao;
    private Bitmap bitmap;

    // 用于设置多次点击同一按钮时重复跳转同一界面
    private int mCurrentType = -1;

    private GifView mIvGoodsImage;
    private GoodsImageView mGivGoodsImage;
    private BarView mBvYellow;
    private BarView mBvRed;
    private BarView mBvBlue;
    private BarView mBvWhite;
    private RelativeLayout mRlVideoBg;
    private RelativeLayout mRlVideoBg2;
    private MyVideoView mVvVideo;
    private RelativeLayout mRlVideoFg;
    private TextView mTvPrice;
    private Button mBtAmount1;
    private Button mBtAmount2;
    private TextView mTvTips;
    private LinearLayout mLlPayMethod;
    private Button mBtPayCash;
    private Button mBtPayCard;
    private Button mBtPayMobile;
    private Button mBtPayFace;
    private ImageView mIvPayImage;
    private ImageView mIvPoster;
    private TextView mTvIntro;
    private ImageView mIvOutResult;
    private FrameLayout mFlInfo;
    private GifView mGvSnow;

    private boolean isVideoBgBig = false;

    private GoodsModel mGoods;
    private String mOrder;
    private String mCode;
    private boolean isPickGoods = false;
    private boolean isFromList = false;

    private int mBuyAmount = 1; //要购买商品的数量
    private int mCurrentBuyCount = 0; //当前已经出货的商品数量

    MediaController mController;

    private boolean isMobileLoading = false;

    private BaiduFaceReceiver mBaidufaceReceiver;
    public static String BAIDU_FACE_PAY_SUCCESS = "baidu.face.pay.success";
    public static String BAIDU_FACE_PAY_FAIL = "baidu.face.pay.failed";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pay, container, false);

        //动态申请camera权限
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 101);

        mBaidufaceReceiver = new BaiduFaceReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAIDU_FACE_PAY_SUCCESS);
        getActivity().registerReceiver(mBaidufaceReceiver, filter);

        showTop();
        //hideBottom();
        showBottom(false, false);

        ImageView cool_circle_02 = (ImageView) view.findViewById(R.id.cool_circle_02);
        ImageView cool_circle_03 = (ImageView) view.findViewById(R.id.cool_circle_03);
        ImageView cool_circle_04 = (ImageView) view.findViewById(R.id.cool_circle_04);
        ImageView cool_circle_05 = (ImageView) view.findViewById(R.id.cool_circle_05);

        mIvGoodsImage = view.findViewById(R.id.iv_goods_image);
        mGivGoodsImage = view.findViewById(R.id.giv_goods_image);
        mBvYellow = view.findViewById(R.id.bv_bar_yellow);
        mBvRed = view.findViewById(R.id.bv_bar_red);
        mBvBlue = view.findViewById(R.id.bv_bar_blue);
        mBvWhite = view.findViewById(R.id.bv_bar_white);
        mRlVideoBg = view.findViewById(R.id.rl_video_bg);
        mRlVideoBg2 = view.findViewById(R.id.rl_video_bg2);
        mVvVideo = view.findViewById(R.id.vv_video);
        mRlVideoFg = view.findViewById(R.id.rl_video_fg);
        mTvPrice = view.findViewById(R.id.tv_price);
        mBtAmount1 = view.findViewById(R.id.bt_amount_1);
        mBtAmount2 = view.findViewById(R.id.bt_amount_2);
        mTvTips = view.findViewById(R.id.tv_tips);
        mLlPayMethod = view.findViewById(R.id.ll_pay_method);
        mBtPayCash = view.findViewById(R.id.bt_pay_cash);
        mBtPayCard = view.findViewById(R.id.bt_pay_card);
        mBtPayMobile = view.findViewById(R.id.bt_pay_mobile);
        mBtPayFace = view.findViewById(R.id.bt_pay_face);
        mIvPayImage = view.findViewById(R.id.iv_pay_image);
        mIvPoster = view.findViewById(R.id.iv_poster);
        mTvIntro = view.findViewById(R.id.tv_intro);
        mIvOutResult = view.findViewById(R.id.iv_out_result);
        mFlInfo = view.findViewById(R.id.fl_info);
        mGvSnow = view.findViewById(R.id.gv_snow);

        zhezhao = view.findViewById(R.id.zhezhao);

        try {
            bitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.zhezhao);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        BitmapTouchChecker btc = new BitmapTouchChecker(bitmap);
        btc.setListener(this);
        zhezhao.setTouchChecker(btc);

        rotateAnimation(cool_circle_02, 15 * 1000, -20f, 100f, true);
        rotateAnimation(cool_circle_03, 12 * 1000, 100f, -15f, true);
        rotateAnimation(cool_circle_04, 8 * 1000, 360, 0f, false);
        rotateAnimation(cool_circle_05, 10 * 1000, 0f, 360f, false);

        mBvRed.setVisibility(View.GONE);
        mBvBlue.setVisibility(View.GONE);
        mBvWhite.setVisibility(View.GONE);

        mBtAmount1.setOnClickListener(this);
        mBtAmount1.setSelected(true);
        mBtAmount2.setOnClickListener(this);
        mBtAmount2.setSelected(false);

        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessage(0);

        Bundle bundle = getArguments();
        if (bundle == null) {
            mLogger.e("参数为空");
            return view;
        }
        String goodsJson = bundle.getString(PARAM_GOODS);
        mCode = bundle.getString(PARAM_CODE);
        boolean isSelect = bundle.getBoolean(PARAM_IS_SELECT, false);
        isFromList = bundle.getBoolean(PARAM_IS_LIST, false);
        mGoods = GoodsModel.fromJson(goodsJson);
        //setting goods
        updatePrice();
        showGoodsImage();
//        mTvGoodsName.setText(String.format(getString(R.string.pay_goods_name), mGoods.getName()));
//        mTvGoodsPrice.setText(String.format(getString(R.string.pay_goods_price), Tools.priceFormat(String.valueOf(mGoods.getPrice()))));
//        setImage(mIvGoodsImage, mGoods.getImage());

        //setting pay method
        int countPayMethod = 4;
        if (!Configure.isCash) {
            mBtPayCash.setVisibility(View.GONE);
            countPayMethod--;
        }
        mBtPayCash.setOnClickListener(view1 -> payCash());
        if (!Configure.isCard) {
            mBtPayCard.setVisibility(View.GONE);
            countPayMethod--;
        }
        mBtPayCard.setOnClickListener(view2 -> payCard());
        if (!Configure.isMobile) {
            mBtPayMobile.setVisibility(View.GONE);
            countPayMethod--;
        }
        mBtPayMobile.setOnClickListener(view3 -> payMobile());
        if (!Configure.isFace) {
            mBtPayFace.setVisibility(View.GONE);
            countPayMethod--;
        }
        mBtPayFace.setOnClickListener(view4 -> payFace());

        DriverThread.getInstance().setOnOutGoodsListener(this);
        //setting order
        mOrder = Configure.getMacNo() + Tools.getCurrentTime();

        //提货码
        if (mCode != null && !"".equals(mCode)) {
            mTvTips.setText(R.string.pay_out_waiting);
            setPayState(PAY_STATE_RESULT);
            isPickGoods = true;
            SimpleDateFormat sd = new SimpleDateFormat("HHmmss", Locale.US);
            String tradeTrace = sd.format(new Date());
            if (!DriverThread.getInstance().outGoods(mGoods.getBox(), mGoods.getColumn(), mGoods.getPrice(), DriverThread.OUT_GOODS_TIHUO, tradeTrace, mOrder)) {
                TaskThreadPool.addTaskAndRun(new PickCodeReleaseTask(mCode, true));
            }
        } else {
            /*if(isSelect) //物理按键选货，无脑进行手机支付
            {
                payMobile();
            }
            else if(countPayMethod == 1) //如果只开启了一种支付方式
            {
                if(Configure.isCash)
                {
                    payCash();
                }
                else if(Configure.isCard)
                {
                    payCard();
                }
                else if(Configure.isMobile)
                {
                    payMobile();
                }
            }*/
        }

        mHandler.sendEmptyMessageDelayed(1, 300);

        return view;
    }

    private void rotateAnimation(ImageView imageView, long time, float fromDegrees, float toDegrees, boolean isReverse) {
        AnimationSet animationSet = new AnimationSet(true);
        RotateAnimation rotateAnimation = new RotateAnimation(fromDegrees, toDegrees, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(time);//设置动画持续时间
        rotateAnimation.setRepeatCount(-1);//设置重复次数
        rotateAnimation.setFillAfter(true);//动画执行完后是否停留在执行完的状态
        if (isReverse) {
            rotateAnimation.setRepeatMode(Animation.REVERSE);    //重新从头执行
        }
        animationSet.addAnimation(rotateAnimation);
        imageView.setAnimation(animationSet);

    }

    /**
     * 重设倒计时
     */
    public void resetCountDown(int time) {
        if (time > 0)
            mDuration = time;
    }

    private void payCash() {
        resetCountDown(COUNT_DOWN);
        setPayState(PAY_STATE_CASH);
        TaskThreadPool.addTaskAndRun(new AvmPayTask(mOrder + "-cash", mGoods, DriverThread.OUT_GOODS_CASH, mBuyAmount));
        //mLlPayMethod.setVisibility(View.GONE);
    }

    private void payCard() {
        resetCountDown(COUNT_DOWN);
        setPayState(PAY_STATE_CARD);
        TaskThreadPool.addTaskAndRun(new AvmPayTask(mOrder + "-card", mGoods, DriverThread.OUT_GOODS_TRANSCARD, mBuyAmount));
        //mLlPayMethod.setVisibility(View.GONE);
    }

    @SuppressLint("StaticFieldLeak")
    private void payMobile() {
        resetCountDown(COUNT_DOWN);
        setPayState(PAY_STATE_MOBILE);

        if (isMobileLoading) {
            return;
        }

        new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected void onPreExecute() {
                isMobileLoading = true;
            }

            @Override
            protected Boolean doInBackground(Void... voids) {
                Socket socket = null;
                InetSocketAddress address = null;
                String ip;
                int port = 6001;

                ip = Configure.getConfigData(Configure.CONFIG_PAY_IP);
                try {
                    port = Integer.parseInt(Configure.getConfigData(Configure.CONFIG_PAY_PORT));
                } catch (NumberFormatException e) {

                }

                socket = new Socket();
                try {
                    socket.setSoTimeout(5000);
                    address = new InetSocketAddress(ip, port);
                    socket.connect(address, 5000);
                    socket.setKeepAlive(true);
                } catch (IOException e) {
                    return false;
                } finally {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
                return true;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (result) {
                    String price = Tools.priceFormat(String.valueOf(mGoods.getPrice() * mBuyAmount));
                    StringBuffer url = new StringBuffer();
                    url.append(Configure.getConfigData(Configure.CONFIG_PAY_URL));
                    url.append("?");
                    StringBuffer param = new StringBuffer();
                    param.append("ddh=").append(mOrder).append("&"); //订单号
                    param.append("jqh=").append(Configure.getMacNo()).append("&"); //售货机编号
                    param.append("price=").append(price).append("&"); //价格
                    param.append("shh=").append(Configure.getConfigData(Configure.CONFIG_PAY_ID)).append("&"); //商户号
                    param.append("spbh=").append(mGoods.getCode()); //商品ID
                    String sign = ETEncrypt.sign(mOrder, price, param.toString());
                    url.append(param);
                    if (sign != null) {
                        url.append("&sign=").append(sign);
                    }
                    mLogger.i("三码合一地址:" + url.toString());
                    if (!createQRImage(url.toString())) {
                        mIvPayImage.setImageResource(R.drawable.qr_failed);
                        resetCountDown(COUNT_DOWN_RESULT);
                    } else {
                        TaskThreadPool.addTaskAndRun(new MobilePayTask(mOrder + "-mobile", mGoods, mBuyAmount));
                    }
                } else {
                    mIvPayImage.setImageResource(R.drawable.qr_failed);
                    resetCountDown(COUNT_DOWN_RESULT);
                }
                isMobileLoading = false;
                super.onPostExecute(result);
            }
        }.execute();
    }

    private void payFace() {
        resetCountDown(COUNT_DOWN);
        setPayState(PAY_STATE_FACE);
        //TODO
        Intent intent=new Intent(getActivity(), BaiduFacePayActivity.class);
        intent.putExtra("order",mOrder);
        intent.putExtra("goodsName",mGoods.getName());
        intent.putExtra("goodsPrice",mGoods.getPrice());
        intent.putExtra("buyAmount",mBuyAmount);
        startActivity(intent);

    }

    /**
     * 将文字转换成二维码并显示
     *
     * @param text
     * @return
     */
    public boolean createQRImage(String text) {
        int QR_WIDTH = 200;
        int QR_HEIGHT = 200;
        try {
            EnumMap<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, QR_HEIGHT,
                    QR_HEIGHT, hints);

            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            mIvPayImage.setImageBitmap(bitmap);

            return true;

        } catch (WriterException e) {
            return false;
        }
    }

    private void setPayState(final int pState) {
        switch (pState) {
            case PAY_STATE_CHOOSE:
                mTvTips.setText(R.string.pay_choose);
                mBtPayCash.setEnabled(true);
                mBtPayCard.setEnabled(true);
                mBtPayMobile.setEnabled(true);
                mBtPayFace.setEnabled(true);
                mLlPayMethod.setVisibility(View.VISIBLE);
                mIvPayImage.setVisibility(View.INVISIBLE);
                mBtAmount1.setEnabled(true);
                mBtAmount2.setEnabled(true);
                break;
            case PAY_STATE_CASH:
                mBtPayCash.setSelected(true);
                mBtPayCard.setSelected(false);
                mBtPayMobile.setSelected(false);
                mBtPayFace.setSelected(false);
                mTvTips.setText(R.string.pay_cash);
                mBtPayCash.setEnabled(false);
//                mBtPayCard.setEnabled(false);
//                mBtPayMobile.setEnabled(false);
//                mBtPayFace.setEnabled(false);
                mLlPayMethod.setVisibility(View.VISIBLE);
                mIvPayImage.setImageResource(R.drawable.icon_cash);
                mIvPayImage.setVisibility(View.VISIBLE);
                mBtAmount1.setEnabled(false);
                mBtAmount2.setEnabled(false);
                isFromList = false;
                break;
            case PAY_STATE_CARD:
                mBtPayCash.setSelected(false);
                mBtPayCard.setSelected(true);
                mBtPayMobile.setSelected(false);
                mBtPayFace.setSelected(false);
                mTvTips.setText(R.string.pay_card);
//                mBtPayCash.setEnabled(false);
                mBtPayCard.setEnabled(false);
//                mBtPayMobile.setEnabled(false);
//                mBtPayFace.setEnabled(false);
                mLlPayMethod.setVisibility(View.VISIBLE);
                mIvPayImage.setImageResource(R.drawable.icon_card);
                mIvPayImage.setVisibility(View.VISIBLE);
                mBtAmount1.setEnabled(false);
                mBtAmount2.setEnabled(false);
                isFromList = false;
                break;
            case PAY_STATE_MOBILE:
                mBtPayCash.setSelected(false);
                mBtPayCard.setSelected(false);
                mBtPayMobile.setSelected(true);
                mBtPayFace.setSelected(false);
                mTvTips.setText(R.string.pay_mobile);
//                mBtPayCash.setEnabled(false);
//                mBtPayCard.setEnabled(false);
                mBtPayMobile.setEnabled(false);
//                mBtPayFace.setEnabled(false);
                mLlPayMethod.setVisibility(View.VISIBLE);
                mIvPayImage.setImageResource(R.drawable.qr_ing);
                mIvPayImage.setVisibility(View.VISIBLE);
                mBtAmount1.setEnabled(false);
                mBtAmount2.setEnabled(false);
                isFromList = false;
                break;
            case PAY_STATE_RESULT:
                mLlPayMethod.setVisibility(View.GONE);
                mIvPayImage.setVisibility(View.GONE);
                mBtAmount1.setEnabled(false);
                mBtAmount2.setEnabled(false);
                break;
            case PAY_STATE_FACE:
                mBtPayCash.setSelected(false);
                mBtPayCard.setSelected(false);
                mBtPayMobile.setSelected(false);
                mBtPayFace.setSelected(true);
                mTvTips.setText(R.string.pay_face);
//                mBtPayCash.setEnabled(false);
//                mBtPayCard.setEnabled(false);
//                mBtPayMobile.setEnabled(false);
                mBtPayFace.setEnabled(false);
                mLlPayMethod.setVisibility(View.VISIBLE);
                mIvPayImage.setImageResource(R.drawable.icon_baiduface);
                mIvPayImage.setVisibility(View.VISIBLE);
                mBtAmount1.setEnabled(false);
                mBtAmount2.setEnabled(false);
                isFromList = false;
                break;
        }
    }

    private void updatePrice() {
        mTvPrice.setText(String.format(getString(R.string.goods_price), Tools.priceFormat(String.valueOf(mGoods.getPrice() * mBuyAmount))));
    }

    private void updateCountDown() {
        mBvYellow.setLeftText(getString(R.string.pay_count_down));
        String second = Tools.addLeftZero(String.valueOf(mDuration), 2);
        mBvYellow.setRightText(String.format(getString(R.string.pay_second), second));
        int percent = mDuration * 100 / COUNT_DOWN;
        mBvYellow.setBarDrawable(R.drawable.bar_orange);
        mBvYellow.setBarPercent(percent);
    }

    private void showGoodsImage() {
        if (mGivGoodsImage.setGoods(mGoods.getCode())) {
            mGivGoodsImage.setVisibility(View.VISIBLE);
            mIvGoodsImage.setVisibility(View.GONE);
        } else {
            final File gifFile = new File(AppApplication.path + "/images/goods_image/" + String.valueOf(mGoods.getCode()) + "/0.gif");
            try {
                FileInputStream fis = new FileInputStream(gifFile);
                mIvGoodsImage.setGifImage(fis);
                mIvGoodsImage.setGifImageType(GifView.GifImageType.COVER);
                mIvGoodsImage.showAnimation();
                mGivGoodsImage.setVisibility(View.GONE);
                mIvGoodsImage.setVisibility(View.VISIBLE);
            } catch (FileNotFoundException e) {
                mGivGoodsImage.setVisibility(View.GONE);
                mIvGoodsImage.setVisibility(View.GONE);
                return;
            }
        }
    }

    private void playVideo() {
        File videoFile = new File(AppApplication.path + "/images/goods_image/" + String.valueOf(mGoods.getCode()) + "/video.mp4");
        if (!videoFile.exists()) {
            mVvVideo.setVisibility(View.GONE);
            String video = Configure.getConfigData(Configure.MAIN_VIDEO_NAMES);
            if (video == null && "".equals(video)) {
                mLogger.e("no video files");
                return;
            }
            String[] videoNames = video.split(";");
            if (videoNames == null || videoNames.length < 1) {
                return;
            }
            Random rand = new Random();
            int pos = rand.nextInt(videoNames.length);
            videoFile = new File(AppApplication.path + "/video/" + videoNames[pos]);
            if (!videoFile.exists()) {
                return;
            }
        }
        String fileName = videoFile.getAbsolutePath();
        mVvVideo.setVideoPath(videoFile.getAbsolutePath());
        mController = new MediaController(getActivity());
        // 隐藏播放条
        mController.setVisibility(View.GONE);
        mController.setEnabled(false);
        mVvVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mVvVideo.setVideoPath(fileName);
                mVvVideo.setMediaController(mController);
                mController.setMediaPlayer(mVvVideo);
                mVvVideo.setEnabled(false);
                mController.setEnabled(false);
                mVvVideo.start();
            }
        });
        mVvVideo.setMediaController(mController);
        mController.setMediaPlayer(mVvVideo);
        mVvVideo.setEnabled(false);
        mVvVideo.start();
        mVvVideo.setVisibility(View.VISIBLE);
        mRlVideoFg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (isVideoBgBig) {
                    isVideoBgBig = false;
                    mRlVideoBg.setVisibility(View.VISIBLE);
                    mRlVideoBg2.setVisibility(View.INVISIBLE);
                    FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mVvVideo.getLayoutParams();
                    lp.width = 400;
                    lp.height = 230;
                    lp.setMargins(98, 130, 0, 0);
                    mVvVideo.setLayoutParams(lp);
                } else {
                    isVideoBgBig = true;
                    mRlVideoBg.setVisibility(View.INVISIBLE);
                    mRlVideoBg2.setVisibility(View.VISIBLE);
                    FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mVvVideo.getLayoutParams();
                    lp.width = 600;
                    lp.height = 320;
                    lp.setMargins(47, 42, 0, 0);
                    mVvVideo.setLayoutParams(lp);
                }
            }
        });
    }

    private void initGoodsInfo() {
        playVideo();
        if (mGoods.getTemperatureState() == ColumnModel.TEMPERATURE_COLD) {
            mGvSnow.setGifImage(R.drawable.anime_snow);
            mGvSnow.setGifImageType(GifView.GifImageType.COVER);
            mGvSnow.showAnimation();
            mGvSnow.setVisibility(View.VISIBLE);
        }
        File jsonFile = new File(AppApplication.path + "/images/goods_image/" + String.valueOf(mGoods.getCode()) + "/goods.json");
        //mLogger.i("json:" + jsonFile.getAbsolutePath());
        if (jsonFile.exists()) {
            //mLogger.i("json file exist");
            String content = FileTools.ReadFile(jsonFile.getAbsolutePath());
            if (content == null || "".equals(content)) {
                mBvRed.setVisibility(View.GONE);
                mBvBlue.setVisibility(View.GONE);
                mBvWhite.setVisibility(View.GONE);
            } else {
                //mLogger.i("json:" + content);
                JSONObject object;
                try {
                    object = new JSONObject(content);
                    String leftText1 = object.getString("leftText1");
                    int percent1 = object.getInt("percent1");
                    String rightText1 = object.getString("rightText1");
                    if (leftText1 == null || "".equals(leftText1) || rightText1 == null || "".equals(rightText1)) {
                        mBvRed.setVisibility(View.GONE);
                    } else {
                        mBvRed.setLeftText(leftText1);
                        mBvRed.setRightText(rightText1);
                        mBvRed.setBarDrawable(R.drawable.bar_red);
                        mBvRed.setBarPercent(percent1);
                        mBvRed.setVisibility(View.VISIBLE);
                    }
                    String leftText2 = object.getString("leftText2");
                    int percent2 = object.getInt("percent2");
                    String rightText2 = object.getString("rightText2");
                    if (leftText2 == null || "".equals(leftText2) || rightText2 == null || "".equals(rightText2)) {
                        mBvBlue.setVisibility(View.GONE);
                    } else {
                        mBvBlue.setLeftText(leftText2);
                        mBvBlue.setRightText(rightText2);
                        mBvBlue.setBarDrawable(R.drawable.bar_blue);
                        mBvBlue.setBarPercent(percent2);
                        mBvBlue.setVisibility(View.VISIBLE);
                    }
                    String leftText3 = object.getString("leftText3");
                    int percent3 = object.getInt("percent3");
                    String rightText3 = object.getString("rightText3");
                    if (leftText3 == null || "".equals(leftText3) || rightText3 == null || "".equals(rightText3)) {
                        mBvWhite.setVisibility(View.GONE);
                    } else {
                        mBvWhite.setLeftText(leftText3);
                        mBvWhite.setRightText(rightText3);
                        mBvWhite.setBarDrawable(R.drawable.bar_yellow);
                        mBvWhite.setBarPercent(percent3);
                        mBvWhite.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                    mLogger.e(e.toString());
                    return;
                }
            }
        } else {
            mBvRed.setVisibility(View.GONE);
            mBvBlue.setVisibility(View.GONE);
            mBvWhite.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackButtonPressed() {
        super.onBackButtonPressed();
        goToFragment(MainActivity.FRAGMENT_HOME, null);
    }

    @Override
    public void onDestroyView() {
        if (mHandler != null) {
            mHandler.removeMessages(0);
            mHandler.removeMessages(1);
        }
        if (mVvVideo != null) {
            if (mVvVideo.isPlaying()) {
                mVvVideo.stopPlayback();
            }
        }

        if (mBaidufaceReceiver != null) {
            getActivity().unregisterReceiver(mBaidufaceReceiver);
        }

        super.onDestroyView();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.bt_amount_1:
                resetCountDown(COUNT_DOWN);
                mBuyAmount = 1;
                mBtAmount1.setSelected(true);
                mBtAmount2.setSelected(false);
                updatePrice();
                break;
            case R.id.bt_amount_2:
                resetCountDown(COUNT_DOWN);
                mBuyAmount = 2;
                mBtAmount1.setSelected(false);
                mBtAmount2.setSelected(true);
                updatePrice();
                break;
        }
    }

    @Override
    public void onClickSwitchListener(final int type) {
        if (type == 1 && mCurrentType != 1) {
            zhezhao.setBackgroundResource(R.drawable.jianjie_0);
            mTvIntro.setVisibility(View.GONE);
            mFlInfo.setVisibility(View.GONE);
            //海报
            File posterFile = new File(AppApplication.path + "/images/goods_image/" + String.valueOf(mGoods.getCode()) + "/poster.png"); //图片大小 400X230
            //mLogger.i("poster:" + posterFile.getAbsolutePath());
            if (posterFile.exists()) {
                //mLogger.i("exist");
                mIvPoster.setImageBitmap(BitmapFactory.decodeFile(posterFile.getAbsolutePath()));
                mIvPoster.setVisibility(View.VISIBLE);
                mFlInfo.setVisibility(View.VISIBLE);
            } else {
                //mLogger.i("not exist");
                mIvPoster.setVisibility(View.GONE);
            }
        } else if (type == 3 && mCurrentType != 3) {
            zhezhao.setBackgroundResource(R.drawable.haibao_0);
            mIvPoster.setVisibility(View.GONE);
            mFlInfo.setVisibility(View.GONE);
            //简介
            File introFile = new File(AppApplication.path + "/images/goods_image/" + String.valueOf(mGoods.getCode()) + "/intro.txt");
            //mLogger.i("intro:" + introFile.getAbsolutePath());
            if (introFile.exists()) {
                String content = FileTools.ReadFile(introFile.getAbsolutePath());
                if (content == null || "".equals(content)) {
                    mTvIntro.setVisibility(View.GONE);
                } else {
                    //mLogger.i("intro:" + content);
                    mTvIntro.setText(content);
                    mTvIntro.setVisibility(View.VISIBLE);
                    mFlInfo.setVisibility(View.VISIBLE);
                }
            } else {
                mIvPoster.setVisibility(View.GONE);
            }
        }
        mCurrentType = type;
    }

    @Override
    public void onOutGoods(final int result, int box, int column, int goodsId, int price, String tradeTrace, String machTrace, String type, int errorCode) {
        if (getActivity() == null) {
            return;
        }
        getActivity().runOnUiThread(() -> {
            if (result == OnOutGoodsListener.RESULT_OK) {
                if (isPickGoods) {
                    mTvTips.setText(R.string.pay_out_success);
                    mIvOutResult.setBackgroundResource(R.drawable.out_success);
                    mIvOutResult.setVisibility(View.VISIBLE);
                    resetCountDown(COUNT_DOWN_RESULT);
                    setPayState(PAY_STATE_RESULT);
                    TaskThreadPool.addTaskAndRun(new PickCodeReleaseTask(mCode, false));
                } else {
                    mCurrentBuyCount++;
                    if (mCurrentBuyCount < mBuyAmount) {
                        mTvTips.setText(String.format(getString(R.string.pay_out_success_num), String.valueOf(mCurrentBuyCount)));
                        resetCountDown(COUNT_DOWN);
                        setPayState(PAY_STATE_RESULT);
                    } else {
                        mTvTips.setText(R.string.pay_out_success);
                        mIvOutResult.setBackgroundResource(R.drawable.out_success);
                        mIvOutResult.setVisibility(View.VISIBLE);
                        resetCountDown(COUNT_DOWN_RESULT);
                        setPayState(PAY_STATE_RESULT);
                    }
                }
            } else {
                mTvTips.setText(R.string.pay_out_failed);
                mIvOutResult.setBackgroundResource(R.drawable.out_failed);
                mIvOutResult.setVisibility(View.VISIBLE);
                resetCountDown(COUNT_DOWN_RESULT);
                setPayState(PAY_STATE_RESULT);
                if (isPickGoods) {
                    TaskThreadPool.addTaskAndRun(new PickCodeReleaseTask(mCode, true));
                }
            }
        });
    }


    private class BaiduFaceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(PayFragment.BAIDU_FACE_PAY_SUCCESS)) {
                //出货操作
                SimpleDateFormat sd = new SimpleDateFormat("HHmmss", Locale.US);
                String tradeTrace = sd.format(new Date());
                if (!DriverThread.getInstance().outGoods(mGoods.getBox(), mGoods.getColumn(), mGoods.getPrice(), DriverThread.OUT_GOODS_BAIPAY, tradeTrace, mOrder)) {
                    mTvTips.setText(R.string.pay_out_failed);
                    mIvOutResult.setBackgroundResource(R.drawable.out_failed);
                    mIvOutResult.setVisibility(View.VISIBLE);
                    resetCountDown(COUNT_DOWN_RESULT);
                    setPayState(PAY_STATE_RESULT);
                }
            } else if (action.equals(PayFragment.BAIDU_FACE_PAY_FAIL)) {
                //支付失败，提示出货失败
                Toast.makeText(AppApplication.context, "百度人脸识别支付失败", Toast.LENGTH_SHORT).show();

            }
        }
    }

    static class MyHandler extends Handler {

        private SoftReference<PayFragment> mFragment;

        public MyHandler(PayFragment fragment) {
            mFragment = new SoftReference<PayFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mFragment == null || mFragment.get() == null) {
                return;
            }
            switch (msg.what) {
                case 0: //倒计时
                {
                    int duration = mFragment.get().mDuration;
                    if (duration <= 0) {
                        if (mFragment.get().isFromList) {
                            mFragment.get().goToFragment(MainActivity.FRAGMENT_GOODS, null);
                        } else {
                            mFragment.get().goToFragment(MainActivity.FRAGMENT_HOME, null);
                        }
                    } else {
                        mFragment.get().updateCountDown();
                        mFragment.get().mDuration--;
                        sendEmptyMessageDelayed(0, 1000);
                    }
                    break;
                }
                case 1: //初始化商品属性
                {
                    mFragment.get().initGoodsInfo();
                    break;
                }
            }
        }
    }
}
